package com.chianghao.rock.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.chianghao.rock.system.entity.BaseTree;
import com.rock.microshop.common_api.vo.BaseTreeVo;

public class TreeUtils {

	
	@SuppressWarnings("unchecked")
	public static <E extends BaseTreeVo,T extends BaseTree> List<E> toTreeDto(Class<? extends BaseTreeVo> tagerVoClass,List<T> items,Long parentId){
		List<E> list = new ArrayList<E>();
    	for(T bean:items) {
    		if(bean.getParentId().longValue()==parentId.longValue()) {
    			E dto = null;
				try {
					dto = (E) tagerVoClass.newInstance();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				if(dto!=null) {
					BeanUtils.copyProperties(bean, dto);
	    			List<E> childList  = toTreeDto(tagerVoClass,items,bean.getId());
	    			if(childList!=null&&!childList.isEmpty()) {
	    				dto.setChildren(childList);
	    			}
	    			list.add(dto);
				}
    		}
    	}
    	Collections.sort(list, new Comparator<E>() {
			@Override
			public int compare(E o1, E o2) {
				return o1.getSort()-o2.getSort();
			}
		});
    	return list;
	}
	
	
}
